<?php

namespace App\Admin\Metrics\Examples;

use App\Models\User;
use Carbon\Carbon;
use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NewUsers extends Line
{
    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();

        $this->title('新增用户');
        $this->dropdown([
            '7' => '近7天',
            '30' => '近一月',
            '365' => '近一年',
        ]);
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        $baseQuery = User::query();

        // 根据 option 设置查询范围和格式
        $dateFormat = "DATE_FORMAT(created_at, '%m-%d')";

        switch ($request->get('option')) {
            case '365':
                $days = 365;
                $dateFormat = "DATE_FORMAT(created_at, '%Y-%m')";
                break;
            case '30':
                $days = 30;
                break;
            case '7':
            default:
                $days = 7;
                break;
        }

        $startDate = Carbon::now()->subDays($days);

        // 设置通用查询条件
        $baseQuery->whereDate('created_at', '>=', $startDate);

        // 构建 count 查询
        $userCount = clone $baseQuery;
        $totalCount = $userCount->count('id');

        // 构建 group 查询
        $userGroup = clone $baseQuery;
        $groupData = $userGroup
            ->select(
                DB::raw("$dateFormat as date"),
                DB::raw('count(id) as total')
            )
            ->groupBy('date')
            ->get()
            ->toArray();

        // 输出内容和图表
        $this->withContent($totalCount);
        $this->withChart($groupData);
    }

    /**
     * 设置图表数据.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        $date = array_column($data, 'date') ?? [];
        $newData = array_column($data, 'total') ?? [];
        return $this->chart([
            'series' => [
                [
                    'data' => $newData,
                ],
            ],
            'xaxis' => [
                'categories' => $date,
            ],
        ]);
    }

    /**
     * 设置卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content)
    {
        return $this->content(
            <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">{$content}</h2>
    <span class="mb-0 mr-1 text-80">{$this->title}</span>
</div>
HTML
        );
    }
}
